/**
 *  版权所有 Copyright@2016
 */
package com.fairy.core;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
/**
 * [实体转换类,Entity对象转换为Dto对象]
 *
 * @ProjectName: [dubbo_core]
 * @Author: [gaoqingbao]
 * @CreateDate: [2015/01/29 10:39]
 * @Update: [说明本次修改内容] BY [gaoqingbao] [2015/01/29 10:39]
 * @Version: [v1.0]
 */
public class Converter{
	   /**
	    * <p>Dto对象 转换为Entity对象</p>
	    * @param objEntity:entity对象
	    * @param ClsDto:dto对象
	    * @return 转换后的dto对象
	    * @throws NoSuchMethodException
	    * @throws InvocationTargetException
	    * @throws IllegalAccessException
	    * @throws InstantiationException
	    */
	   public static  <T> T convertDto2Entity(Object ClsDto,Class<T> objEntity) {  
		   //UserEntity userEntity=Converter.convertDto2Entity(userDto, UserEntity.class);
	        Map<String,Object> maps = new HashMap<String,Object>();  
	        T  dataBean = null;  
	        try
	        {
		        if(null==ClsDto) 
		        {  
		            return null;  
		        }  
		        Class<?> cls = ClsDto.getClass();  
		        dataBean = objEntity.newInstance();  
		        Field[] fields = cls.getDeclaredFields();  
		        Field[] beanFields = objEntity.getDeclaredFields();  
		        for(Field field:fields)
		        {  
		            String fieldName = field.getName(); 
		            if(!fieldName.equals("serialVersionUID"))
		            {
			            String strGet = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length());  
			            Method methodGet = cls.getDeclaredMethod(strGet);  
			            Object object = methodGet.invoke(ClsDto);  
			            maps.put(fieldName,object==null?"":object);  
		            }
	
		        }  
		  
		        for(Field field:beanFields)
		        {  
		            field.setAccessible(true);  
		            String fieldName = field.getName();  
		            Class<?> fieldType = field.getType();  
		            String fieldValue = maps.get(fieldName)==null?null:maps.get(fieldName).toString();  
		            if(fieldValue!=null&&!"".equals(fieldValue))
		            {  
		                try 
		                {  
		                    if(String.class.equals(fieldType)){  
		                        field.set(dataBean, fieldValue);  
		                    }else if(byte.class.equals(fieldType)){  
		                        field.setByte(dataBean, Byte.parseByte(fieldValue));  
		  
		                    }else if(Byte.class.equals(fieldType)){  
		                        field.set(dataBean, Byte.valueOf(fieldValue));  
		  
		                    }else if(boolean.class.equals(fieldType)){  
		                        field.setBoolean(dataBean, Boolean.parseBoolean(fieldValue));  
		  
		                    }else if(Boolean.class.equals(fieldType)){  
		                        field.set(dataBean, Boolean.valueOf(fieldValue));  
		  
		                    }else if(short.class.equals(fieldType)){ 
								System.out.println(fieldType+"================="+fieldValue+"--------------------");
		                        field.setShort(dataBean, Short.parseShort(fieldValue.trim()));  
		  
		                    }else if(Short.class.equals(fieldType)){  
								System.out.println(fieldType+"================="+fieldValue+"--------------------");
		                        field.set(dataBean, Short.valueOf(fieldValue.trim()));  
		  
		                    }else if(int.class.equals(fieldType)){  
								System.out.println(fieldType+"================="+fieldValue+"--------------------");
		                        field.setInt(dataBean, Integer.parseInt(fieldValue.trim()));  
		  
		                    }else if(Integer.class.equals(fieldType)){  
								System.out.println(fieldType+"================="+fieldValue+"--------------------");
		                        field.set(dataBean, Integer.valueOf(fieldValue.trim()));  
		  
		                    }else if(long.class.equals(fieldType)){  
								System.out.println(fieldType+"================="+fieldValue+"--------------------");
		                        field.setLong(dataBean, Long.parseLong(fieldValue.trim()));  
		  
		                    }else if(Long.class.equals(fieldType)){  
								System.out.println(fieldType+"================="+fieldValue+"--------------------");
		                        field.set(dataBean, Long.valueOf(fieldValue.trim()));  
		  
		                    }else if(float.class.equals(fieldType)){  
								System.out.println(fieldType+"================="+fieldValue+"--------------------");
		                        field.setFloat(dataBean, Float.parseFloat(fieldValue.trim()));  
		  
		                    }else if(Float.class.equals(fieldType)){  
								System.out.println(fieldType+"================="+fieldValue+"--------------------");
		                        field.set(dataBean, Float.valueOf(fieldValue.trim()));  
		  
		                    }else if(double.class.equals(fieldType)){  
								System.out.println(fieldType+"================="+fieldValue+"--------------------");
		                        field.setDouble(dataBean, Double.parseDouble(fieldValue.trim()));  
		  
		                    }else if(Double.class.equals(fieldType)){  
								System.out.println(fieldType+"================="+fieldValue+"--------------------");
		                        field.set(dataBean, Double.valueOf(fieldValue.trim()));  
		  
		                    }else if(Date.class.equals(fieldType)){  
		                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");  
		                        field.set(dataBean, sdf.parse(fieldValue));  
		                    }  
		                } catch (IllegalArgumentException e) {  
		                    e.printStackTrace();  
		                } catch (ParseException e) {  
		                    e.printStackTrace();  
		                }  
		  
		            }  
		        }  
	        }
	        catch(Exception e)
	        {
	        	 e.printStackTrace();  
	        }
	        return dataBean;  
	  
	    }  
	   
	    /** 
	     * <p>将javaBean转换成Map</p> 
	     * @param javaBean javaBean 
	     * @return Map对象 
	     */ 

		public static Map<String,Object> bean2Map(Object bean) throws Exception
		{  

		        Map<String,Object> map = new HashMap<String,Object>();  
		        Field[] fields = null;  
		        fields = bean.getClass().getDeclaredFields();   
		        for (Field field : fields) 
		        {  
		            field.setAccessible(true);  
		            String proName = field.getName();  
		            if(!proName.equals("serialVersionUID"))
		            {  
			            map.put(proName, field.get(bean));  
		            }
	 
		        }  
		        return map;  
		 } 
		public static Map<String,String> bean2Map2(Object bean) throws Exception
		{  
			    Map<String, String> map=BeanUtils.describe(bean);
   
		        return map;  
		 }
		
		 public static <T>T map2bean(T javabean, Map<String, String> map) {  
		        Method[] methods = javabean.getClass().getDeclaredMethods(); 
		       
		        for (Method method : methods) 
		        {  
		            try {  
		                if (method.getName().startsWith("set")) 
		                {  
		                    String field = method.getName();  
		                    field = field.substring(field.indexOf("set") + 3);  
		                    String getterName="get"+field;  
		                    field = field.toLowerCase().charAt(0) + field.substring(1);  
		                    String value=map.get(field);  
		                      
		                    Method getter=javabean.getClass().getMethod(getterName);  
		                    String methodType=getter.getReturnType().getName();  
		                    Object[] cache = new Object[1];  
		                    if(value!=null&&!"".equals(value))
		                    {
			                    if(methodType.equalsIgnoreCase("long")) {  
			                        cache[0] = new Long(value);  
			                    } else if(methodType.equalsIgnoreCase("int")||methodType.equalsIgnoreCase("integer")) {  
			                        cache[0] = new Integer(value);  
			                    } else if(methodType.equalsIgnoreCase("short")) {  
			                        cache[0] = new Short(value);  
			                    } else if(methodType.equalsIgnoreCase("float")) {  
			                        cache[0] = new Float(value);  
			                    } else if(methodType.equalsIgnoreCase("double")) {  
			                        cache[0] = new Double(value);  
			                    } else if(methodType.equalsIgnoreCase("boolean")) {  
			                        cache[0] = new Boolean(value);  
			                    } else if(methodType.equalsIgnoreCase("java.lang.String")) {  
			                        cache[0] = value;  
			                    } else if(methodType.equalsIgnoreCase("java.io.InputStream")) {  
			                          
			                    } else if(methodType.equalsIgnoreCase("char")) {  
			                        cache[0] = (Character.valueOf(value.charAt(0)));  
			                    }
		                    }
  
		                    method.invoke(javabean, cache);  
		                }  
		            } catch (Exception e) 
		            {  
		            	e.printStackTrace();
		            }  
		        }  
		        
		        return javabean;
		 }

		 /** 
		     *  
		     *  
		     * Map转换层Bean，使用泛型免去了类型转换的麻烦。 
		     * @param <T> 
		     * @param map   
		     * @param class1 
		     * @return 
		     */  
		    public static <T> T map2Bean2(Map<String, String> map, Class<T> class1) {  
		        T bean = null;  
		        try {  
		            bean = class1.newInstance();  
		            BeanUtils.populate(bean, map);  
		        } catch (InstantiationException e) {  
		            e.printStackTrace();  
		        } catch (IllegalAccessException e) {  
		            e.printStackTrace();  
		        } catch (InvocationTargetException e) {  
		            e.printStackTrace();  
		        }  
		        return bean;  
		    }  
		 /**
		  * <p>将listBean转换成ListMap</p> 
		  * @param listBean
		  * @return
		  * @throws Exception
		  */
		public static List<Map<String,Object>> ListBean2ListMap(List<Object> listBean) throws Exception
		 {
			
			 List<Map<String,Object>>listMap=new ArrayList<Map<String,Object>>();
			 for(Object bean:listBean)
			 {
				 Map<String,Object> map = bean2Map(bean);  
				 listMap.add(map);
			 }
			 return listMap; 
		 }

		 /**
		  * <p>将List<Map>转化为List<T></p>
		  * @param listMap
		  * @param t
		  * @return
		  * @throws Exception
		  */
		 @SuppressWarnings({ "rawtypes", "unchecked" })
		public static  <T>List<T> ListMap2Listbean(List<Map> listMap,T t) throws Exception
		 {
			 List<T> listBean=new ArrayList<T>();
			 for(Map map:listMap)
			 {
				 T bean =(T) map2bean(t, map);
				 listBean.add(bean);
			 }
			 return listBean;
		 }
}
